package com.example.zxslzw2014_8_11;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    private static Logger logger = LoggerFactory.getLogger(LoggerFactory.class);
    @Autowired
    private CaptchaProperties captchaProperties;
    public static final long session_valid_timeout = 60 * 1000;//1分钟
    //验证码页面
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置返回类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Progma", "No-cache");
        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            lineCaptcha.write(response.getOutputStream());
            //存储Session
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //校验验证码
    @RequestMapping("/check")
    public Boolean check(String inputCode, HttpSession session) {
        //验证码生成的内容，和用户输入的内容进行比较
        if(!StringUtils.hasLength(inputCode)) {
            return false;
        }
        //从Session获取信息
        String saveCode = (String)session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date)session.getAttribute(captchaProperties.getSession().getDate());
        if(inputCode.equals(saveCode)) {
        //如果时间超过1分钟，验证码就失效
            if(saveDate != null && (System.currentTimeMillis() - saveDate.getTime()) < session_valid_timeout) {
                return true;
            }
        }
        return false;
    }
}